<?php

namespace App\Http\Controllers\Api\v1\Goods;

use App\Handlers\KeysHandler;
use App\Http\Controllers\Api\v1\Controller;
use App\Http\Resources\GoodsResource;
use App\Models\Ad;
use App\Models\Configuration;
use App\Models\Goods;
use App\Models\GoodsCategory;
use App\Models\GoodsOrder;
use App\Models\Shopwindow;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class GoodsController extends Controller
{
    /**
     * 商品搜索
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function search(Request $request)
    {
        $keyword = $request->get('keyword');
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $page = $this->paging($page, $limit);

        if(is_numeric($keyword)){
            //查询条件
            $where = [
//            ['type', '=', Goods::TYPE_GOODS],
                ['status', '=', Goods::STATUS_YES],
                ['id' ,'=', $keyword]

            ];
        }else{
            //查询条件
            $where = [
//            ['type', '=', Goods::TYPE_GOODS],
                ['status', '=', Goods::STATUS_YES],
                ['name' ,'like', '%' . $keyword . '%'],
                ['id' ,'like', '%' . $keyword . '%', 'OR']

            ];
        }


        $list = Goods::getList($where, $page, $limit);
        $list = GoodsResource::collection($list);
        return $this->success($list);
    }

    /**
     * 商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function goodsList(Request $request)
    {
        $request->validate([
            'category_id' => 'required|int',
            'page' => 'int',
            'limit' => 'int'
        ]);
        $category_id = $request->get('category_id');
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);

        //展示40个热门商品
        if($category_id == -1){
            $limit = 40;
            if($page > 1){
                return $this->success([]);
            }
        }
        $page = $this->paging($page, $limit);
        $price = $request->get('price', '');
        $profit = $request->get('profit', '');
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        /*
        $list = Cache::get(sprintf(KeysHandler::GOODS_LIST, $category_id, $page, $limit));
        if (!empty($list)) {
            return $this->success($list);
        }
        $lock = Cache::lock(KeysHandler::GOODS_LIST_LOCK, 2);
        if (!$lock->get()) {
            usleep(100000); //睡眠100ms
            return $this->goodsList($request);
        }
        */
        //查询条件
        if($category_id == -1){
            $where = [
                'status' => Goods::STATUS_YES
            ];
        }else{
            $where = [
                'category_id' => $category_id,
                'status' => Goods::STATUS_YES
            ];
        }
        $query = Goods::query()
            ->whereHas('category', function ($query) {
                $query->where('status', GoodsCategory::STATUS_YES);
            })->where($where);

        if((empty($price) && empty($profit)) || $category_id == -1 ){
            $query->inRandomOrder();
        }else{
            if(!empty($price)){
                $query->orderBy('price',$price);
            }
            if(!empty($profit)){
                $query->orderBy('profit',$profit);
            }
        }

        //不展示已添加到橱窗的
        $goods_ids= DB::table('shopwindows')->where('user_id','=',$user->id)->get()->pluck('goods_id')->toArray();
        $query->whereNotIn('id',$goods_ids);

        $query->where('country','=',config('app.goods_country'));

        $query->offset($page)->limit($limit);

         $list = $query->select('id','code', 'category_id', 'name', 'original_price', 'price','profit', 'img','quality')
            ->get();
        if (!$list->isEmpty()) {
            $list = GoodsResource::collection($list);
            //Cache::put(sprintf(KeysHandler::GOODS_LIST, $category_id, $page, $limit), $list, 2);
        }
        //$lock->release();
        return $this->success($list);
    }





    //橱窗商品新增
    public function shopwindowStore(Request $request){
        $request->validate([
            'goods_ids' => 'required'
        ]);
        $goods_ids = explode(",", $request->goods_ids);
        $goods_count = Goods::query()->whereIn('id',$goods_ids)->count();
        if($goods_count == count($goods_ids)){
            $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
            foreach ($goods_ids as $goods_id){
                $insert_data[] = ['user_id'=>$user->id , 'goods_id' => $goods_id,'added_time'=>Carbon::now()];
            }
            DB::table('shopwindows')->insertOrIgnore($insert_data);
        }else{
            return $this->fail(300000,trans('error.' . 300000));
        }
        return $this->success();
    }


    /**
     * 橱窗商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function shopwindowGet(Request $request)
    {
        $request->validate([
            'shelves' => 'required|int',
            'page' => 'int',
            'limit' => 'int'
        ]);
        $shelves = $request->get('shelves',-1);
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $page = $this->paging($page, $limit);
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        //查询条件
        $map['user_id'] = $user->id;
        if($shelves != -1){
            $map['shelves'] = $shelves;
        }
        $goods_ids_arr = DB::table('shopwindows')->where($map)->get()->pluck('added_time','goods_id')->toArray();

        if($shelves ==1){
            $goods_shelves_ids = $goods_ids_arr;
        }else{
            $goods_shelves_ids = DB::table('shopwindows')->where('user_id','=',$user->id)->where('shelves','=',1)->get()->pluck('added_time','goods_id')->toArray();
        }

        $goods_ids = array_keys($goods_ids_arr);
        $where = [
            'status' => Goods::STATUS_YES
        ];
        $whereIn = ['id', $goods_ids];
        $list = Goods::getList($where, $page, $limit,[],[],$whereIn);
        foreach ($list as $goods){
            $goods->shelves = 0;
            $goods->added_time = "";
            if(isset($goods_shelves_ids[$goods->id])){
                $goods->shelves = 1;
                $goods->added_time = Carbon::parse($goods_shelves_ids[$goods->id])->format('Y-m-d');
            }
        }
        if (!$list->isEmpty()) {
            $list = GoodsResource::collection($list);
        }
        return $this->success($list);
    }

    //橱窗商品修改
    public function shopwindowUpdate(Request $request)
    {
        $request->validate([
            'goods_id' => 'required|int',
            'shelves' => 'required'
        ]);
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        $data = ['shelves' => $request->shelves];
        //上架
        if($request->shelves == 1){
            $data['added_time'] = Carbon::now();
        }

        //下架
        if($request->shelves == 0){
            $daystr = date('ymd');
            $key = 'user_shelves_close_num:'.'day:'.$daystr.':u:'.$user->id;
            $num = Cache::has($key)?Cache::get($key):0;
            if($num >= Configuration::getItem('day_shelves_goods_number')){
                return $this->fail(300004,trans('error.' . 300004));
            }
            $num++;
            Cache::put($key,$num);
        }

        DB::table('shopwindows')
            ->where('user_id','=',$user->id)
            ->where('goods_id','=',$request->goods_id)
            ->update($data);
        return $this->success();
    }

    /**
     * 橱窗商品列表---后台
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function userShopwindow(Request $request)
    {
        $request->validate([
            'user_id' => 'required|int',
            'page' => 'int',
            'limit' => 'int'
        ]);
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        //$page = $this->paging($page, $limit);
        //查询条件
        $map['user_id'] = $request->get('user_id');
        $map['shelves'] = 1;
        $goods_ids = DB::table('shopwindows')->where($map)->get()->pluck('goods_id')->toArray();
        $where = [
            'status' => Goods::STATUS_YES
        ];
        $whereIn = ['id', $goods_ids];

        $model = Goods::query()
            ->whereHas('category', function ($query) {
                $query->where('status', GoodsCategory::STATUS_YES);
            });


        $model->where($where);
        $model->whereIn($whereIn[0],$whereIn[1]);
        $list =  $model->limit($limit)
            ->orderBy('id', 'desc')
            ->select('id','code', 'category_id', 'name', 'original_price', 'price','profit', 'img','quality')
            ->paginate($limit);;
        return $this->success([
            'list' =>GoodsResource::collection($list->items()),
            'paginate' => $this->paginate($list)

        ]);
    }


    /**
     * 推广商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function shopGoodsAdGet(Request $request)
    {

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $page = $this->paging($page, $limit);
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        //查询条件
        $ads_goods_ids= DB::table('ads')->where('user_id','=',$user->id)->whereColumn('finish_click','<','click')->get()->pluck('goods_id')->toArray();

        //已上架商品
        $goods_shelves_ids = DB::table('shopwindows')->where('user_id','=',$user->id)->where('shelves','=',1)->get()->pluck('added_time','goods_id')->toArray();

        $where = [
            'status' => Goods::STATUS_YES
        ];
        $whereIn = ['id', $ads_goods_ids];
        $list = Goods::getList($where, $page, $limit,[],[],$whereIn);
        foreach ($list as $goods){
            $goods->shelves = 0;
            $goods->added_time = "";
            if(isset($goods_shelves_ids[$goods->id])){
                $goods->shelves = 1;
                $goods->added_time = Carbon::parse($goods_shelves_ids[$goods->id])->format('Y-m-d');
            }
        }
        if (!$list->isEmpty()) {
            $list = GoodsResource::collection($list);
        }
        return $this->success($list);
    }


    /**
     * 店铺商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function shopGoodsList(Request $request)
    {
        $request->validate([
            'category_id' => 'int',
            'page' => 'int',
            'limit' => 'int'
        ]);

        $user = User::getShop($request->header('tiktokno'));
        $this->checkShop($user);

        $category_id = $request->get('category_id');
        $key = $request->get('key');
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $page = $this->paging($page, $limit);


        $query = Goods::query();
        $query->select('id','code', 'category_id', 'name', 'price','profit', 'img','quality');

        $query->whereHas('category', function ($query) {
            $query->where('status', GoodsCategory::STATUS_YES);
        });
        $query->whereHas('shopwindows', function ($query)use($user) {
            $query->where('shelves', 1)->where('user_id','=',$user->id);
        });

        if($category_id){
            $query->where('category_id','=',$category_id);
        }
        if($key){
            $query->where('name','like',"%{$key}%");
        }
        $query->where('status','=',Goods::STATUS_YES);
        $query->where('country','=',config('app.goods_country'));

        $list = $query->offset($page)->limit($limit)->get();
        if (!$list->isEmpty()) {
            $list = GoodsResource::collection($list);
        }
        return $this->success($list);
    }

    /**
     * 店铺首页商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function shopGoodsIndex(Request $request)
    {
        $request->validate([
            'page' => 'int',
            'limit' => 'int'
        ]);
        $user = User::getShop($request->header('tiktokno'));
        $this->checkShop($user);

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $page = $this->paging($page, $limit);

        $query = Goods::query();
        $query->select('id','code', 'category_id', 'name', 'price','profit', 'img','quality');

        $query->whereHas('category', function ($query) {
            $query->where('status', GoodsCategory::STATUS_YES);
        });
        $query->whereHas('shopwindows', function ($query)use($user) {
            $query->where('shelves', 1)->where('user_id','=',$user->id);
        });
        $query->where('status','=',Goods::STATUS_YES);
        $query->where('country','=',config('app.goods_country'));
        //$query->inRandomOrder();
        $list = $query->offset($page)->limit($limit)->get();
        if (!$list->isEmpty()) {
            $list = GoodsResource::collection($list);
        }
        return $this->success($list);
    }


    /**
     * 店铺推广商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function shopGoodsAdlist(Request $request)
    {
        $user = User::getShop($request->header('tiktokno'));
        $this->checkShop($user);

        $query = Goods::query();
        $query->select('id','code', 'category_id', 'name', 'price','profit', 'img','quality');

        $query->whereHas('category', function ($query) {
            $query->where('status', GoodsCategory::STATUS_YES);
        });
        $query->whereHas('ads', function ($query)use($user) {
            $query->where('user_id','=',$user->id)->whereColumn('finish_click','<','click');
        });

        $query->where('status','=',Goods::STATUS_YES);
        $query->where('country','=',config('app.goods_country'));

        $list = $query->get();
        if (!$list->isEmpty()) {
            $list = GoodsResource::collection($list);
        }
        $endtime = Ad::query()->where('user_id','=',$user->id)->whereColumn('finish_click','<','click')->orderByDesc('created_at')->value('created_at');
        $data['list'] = $list;
        $data['endtime'] = $endtime ? Carbon::parse($endtime)->addHours(24)->timestamp : 0;
        return $this->success($data);
    }


    /**
     * 商品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function shopDetail(Request $request)
    {
        $request->validate([
            'goods_id' => 'required|int'
        ]);
        $goods = Goods::query()
        ->where('id', $request->goods_id)
        ->where('status', Goods::STATUS_YES)
        ->whereHas('category', function ($query) {
            $query->where('status', GoodsCategory::STATUS_YES);
        })
        ->select('id','code', 'category_id', 'name', 'price','profit', 'img','quality', 'imgs', 'detail')
        ->first();
        if (empty($goods)) {
            return $this->fail(300000, trans('error.300000'));
        }


        return $this->success(GoodsResource::make($goods));
    }




}
